﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using wnet.admin.Comm;
using System.Collections.Concurrent;
using System.Linq;
using SqlSugar;
using Models;
using wnet.admin.wentcommon;

namespace wnet.admin.CommQueue
{
    /// <summary>
    /// 创建中间队列和处理逻辑
    /// </summary>

    public class AlarmQueue
    {
        private static readonly ConcurrentQueue<AlarmView> _queue = new ConcurrentQueue<AlarmView>();


        private static ISqlSugarClient _sqlSugarClient = SqlSugarConfig.CreateClient();
        

        // 添加到队列的方法
        public static void Enqueue(AlarmView alarmView)
        {
            _queue.Enqueue(alarmView);
        }

        // 处理队列中的项目并写入数据库
        public static async Task ProcessQueueAsync()
        {
            while (!_queue.IsEmpty)
            {
                if (_queue.TryDequeue(out var alarmView))
                {
                    await WriteToDatabaseAsync(alarmView);
                }
            }
        }

        // 模拟写入数据库的方法
        private static async Task WriteToDatabaseAsync(AlarmView alarmView)
        {
            try
            {
                yw_llarmlist parm = new yw_llarmlist();

                parm.alarmdate = alarmView.alarmdate;
                parm.alarmlocation = alarmView.Alarmlocation;
                parm.createtime = DateTime.Now;
                parm.damagelevel = alarmView.AlarmLevel;
                parm.detailinfo = alarmView.AlarmContent;

                await _sqlSugarClient.Insertable<yw_llarmlist>(parm).ExecuteCommandAsync();
            }
            catch (Exception ex)
            {

                LogHelper.WriteLog("ex=" + ex.Message);
            }
            //// 这里是模拟写入数据库的操作
            //Console.WriteLine($"Writing to database: {alarmView.AlarmNo} - {alarmView.AlarmContent}");
            LogHelper.WriteLog("队列=" + Newtonsoft.Json.JsonConvert.SerializeObject(alarmView));
            //await Task.Delay(100); // 模拟异步操作


        }
    }
}